const PENDING = 'pending'; // 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'rejected'; // 失败

class MyPromise {
    constructor(construc) {
      try {
          construc(this.resolve, this.reject)
      } catch (error) {
          
      }
    }

    status = PENDING

    value = undefined;
   
    reason = undefined;

    successCallback = [];

    failCallback = [];

    resolve = value => {
        if (this.status != PENDING) return
        this.status = FULFILLED;
        this.value = value

        while(this.successCallback.length) this.successCallback.shift()() 
    }

    reject = reason => {
        if (this.status != PENDING) return
        this.status = REJECTED;
        this.reason = reason

        while(this.failCallback.length) this.failCallback.shift()()
    }

    then = (successCallback, failCallback) => {
      
        if (this.status == FULFILLED) {
            successCallback(this.value)
        } 

        if (this.status == REJECTED) {
            failCallback(this.reason)
        }

        if (this.status == PENDING) {
            this.successCallback.push(()=>{
                successCallback(this.value)
            })
            this.failCallback.push(()=>{
                failCallback(this.reason)
            })
        }
    }
}

let pro = new MyPromise((resolve, reject)=>{
   setTimeout(()=>{
       resolve(10)
   },1000)
})

pro.then((v)=>{
    console.log(v)
})